import exceptions.OberonException;

import java.io.FileReader;

public class TestDrive {

    static String encodingName = "UTF-8";

    public static String jCupRunSymbolToString(java_cup.runtime.Symbol symbol) {
        return String.format("%s: %s", OberonSymbol.terminalNames[symbol.sym], symbol.value);
    }

    /**
     * 对指定源代码进行词法测试，返回是否通过词法测试
     *
     * @param fileName 测试的源代码文件
     * @return 是否通过词法测试
     */
    public static boolean lexTest(String fileName) {
        try {
            java.io.FileInputStream stream = new java.io.FileInputStream(fileName);
            java.io.Reader reader = new java.io.InputStreamReader(stream, encodingName);
            OberonScanner scanner = new OberonScanner(reader);
            do {
                java_cup.runtime.Symbol symbol = scanner.next_token();
                System.out.println(jCupRunSymbolToString(symbol));
//                System.out.println(symbol.left);
//                System.out.println(symbol.sym);
//                System.out.println(symbol.right);
//                System.out.println(symbol.value);
//                System.out.println(symbol.parse_state);
//                    System.out.println(scanner.yytext());
//                    System.out.println(scanner.yylex());
            } while (!scanner.yyatEOF());
            return true;
//        } catch (LexicalException e) {
//            System.out.println("词法分析异常");
//            System.out.println(e);
        } catch (java.io.FileNotFoundException e) {
            System.out.println("File not found : \"" + fileName + "\"");
        } catch (java.io.IOException e) {
            System.out.println("IO error scanning file \"" + fileName + "\"");
            System.out.println(e);
        } catch (Exception e) {
            System.out.println("Unexpected exception:");
            e.printStackTrace();
        }
        return false; // 此时一定是触发异常导致的
    }

    public static void main(String argv[]) throws Exception {
        System.out.println("hello");
//        lexTest("test");
        String fileName;
        if (argv.length == 0) {
            fileName = "test";
            OberonParser parser = new OberonParser(new OberonScanner(new FileReader(fileName)));
            parser.parse();
            return;
        }
        for (int i = 0; i < argv.length; ++i) {
            try {
                fileName = argv[i];
                OberonParser parser = new OberonParser(new OberonScanner(new FileReader(fileName)));
                System.out.println(jCupRunSymbolToString(parser.parse()));
            } catch (OberonException ex) {
                System.out.println(ex);
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
    }
}
